package com.chatmcp.mcprouter.cli;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 命令行运行器
 * 负责解析和执行命令行参数
 */
@Component
public class CommandRunner implements ApplicationRunner {

    private final Map<String, Command> commands = new HashMap<>();
    private final ApplicationContext context;

    @Autowired
    public CommandRunner(ApplicationContext context) {
        this.context = context;
        
        // 注册命令
        registerCommand("proxy", new ProxyCommand());
        registerCommand("api", new ApiCommand());
        registerCommand("help", new HelpCommand());
        registerCommand("version", new VersionCommand());
    }

    /**
     * 注册命令
     *
     * @param name 命令名称
     * @param command 命令实现
     */
    public void registerCommand(String name, Command command) {
        commands.put(name, command);
    }

    @Override
    public void run(ApplicationArguments args) {
        // 获取命令名称（第一个非选项参数）
        String commandName = "help"; // 默认为帮助命令
        if (args.getNonOptionArgs().size() > 0) {
            commandName = args.getNonOptionArgs().get(0);
        }

        // 获取命令实例
        Command command = commands.getOrDefault(commandName, commands.get("help"));

        // 执行命令
        String[] commandArgs = args.getNonOptionArgs().stream()
                .skip(1)
                .toArray(String[]::new);
        
        try {
            command.execute(context, commandArgs, args);
        } catch (Exception e) {
            System.err.println("命令执行失败: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
} 